<template>
  <div class="signed-agent-detail-product-view">
    <div>
      <el-row>
        <el-col :span="4">
          <el-button
            class="border-btn"
            size="small"
            style="margin-bottom: 20px;"
            @click="addClick"
          >增加代理产品</el-button>
        </el-col>
        <el-col :span="20">
          <div style="display: flex; justify-content: flex-end">
            <el-form
              :inline="true"
              label-position="right"
              label-width="130px"
              size="small"
              class="filter-form-inline"
            >
              <el-row :gutter="10">
                <el-col :span="16">
                  <el-form-item
                    label="产品信息"
                    style="width: 100%"
                  >
                    <el-select
                      v-model="formData.productId"
                      clearable
                      filterable
                      remote
                      reserve-keyword
                      :remote-method="remoteMethod"
                      :loading="loading"
                      placeholder="请选择产品"
                      @change="listSearch"
                    >
                      <el-option
                        v-for="item in products"
                        :key="item.id"
                        :label="item.productPopularName"
                        :value="item.id"
                      />
                    </el-select>

                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="">
                    <filter-popover
                      right="20px"
                      :form-list="formList"
                      @onConfirm="filterDataConfirm"
                      @onReset="filterReset"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-table
      :data="tableData"
      header-cell-class-name="table-header"
      size="medium"
      border
      @row-click="rowClick"
    >
      <el-table-column
        type="tags"
        label="编号"
        fixed="left"
        align="center"
        prop="agentProductNumber"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        type="tags"
        label="产品名称"
        fixed="left"
        align="left"
        header-align="center"
        prop="productPopularName"
        width="150"
        show-overflow-tooltip
      />
      <el-table-column
        type="tags"
        label="批准文号"
        align="center"
        prop="approvalNumber"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        type="tags"
        label="包装规格"
        align="center"
        prop="packSpecs"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        type="tags"
        label="可营销终端"
        align="center"
      >
        <template #default="{row}">
          {{ getLabel('app_mode',row.terminalType) }}
        </template>
      </el-table-column>
      <el-table-column
        type="tags"
        label="代理地区"
        align="center"
        width="200"
      >
        <template #default="{row}">
          <area-list-view :areas="row.region" />
        </template>
      </el-table-column>
      <el-table-column
        type="tags"
        :label="type == 'agent' ? '代理属性' : '兼职属性'"
        align="center"
      >
        <template #default="{row}">

          {{ getLabel( type == 'agent' ? 'agent' : 'agent_person' , row.agentAttribute) }}
        </template>
      </el-table-column>
      <el-table-column
        type="tags"
        label="交易价(元)"
        align="center"
        width="100"
      >
        <template #default="{row}">
          <div>{{ row.tradePrice }}</div>
          <div
            v-if="row.flowStatus == 'DOING' && (row.processDefinitionKey == 'agentProductChangePrice' || row.processDefinitionKey == 'agentPersonProductChangePrice')"
            class="flow-status-color"
          >交易价变更审核中</div>
        </template>
      </el-table-column>
      <el-table-column
        type="tags"
        :label="type == 'agent' ? '代理期限至' : '兼职期限至'"
        align="center"
        width="100"
      >
        <template #default="{row}">
          {{ dateFormat('yyyy-mm-dd',row.agentEndTime) }}
        </template>
      </el-table-column>
      <el-table-column
        type="tags"
        :label="type == 'agent' ? '关联代理合同' : '关联兼职合同'"
        align="left"
        header-align="center"
        width="150"
        prop="contractName"
        show-overflow-tooltip
      />
      <el-table-column
        type="tags"
        label="最底销量"
        align="center"
        width="150"
      >
        <template #default="{row}">

          <div v-if="row.minSale">
            {{ row.minSale }}{{ getLabel('sell_unit',row.sellUnit) }}/{{ getLabel('sell_num_unit',row.minSaleUnit+'') }}
          </div>
          <div v-else>未设置</div>
        </template>
      </el-table-column>
      <el-table-column
        type="tags"
        label="销量保证金(元)"
        align="center"
      >
        <template #default="{row}">

          <div v-if="row.minSalePromise">
            {{ row.minSalePromise }}
          </div>
          <div v-else>未设置</div>
        </template>
      </el-table-column>
      <el-table-column
        type="tags"
        label="负责营销职员"
        align="center"
        prop="headName"
      />
      <el-table-column
        v-if="datas.tradeStatus == 1"
        type="tags"
        label="上月销量"
        align="center"
        prop="lastMonthSale"
        min-width="100px"
      >
        <template #default="{row}">

          <div class="tab-line">
            <div v-if="row.lastMonthSale">{{ row.lastMonthSale }}</div>
            <div v-else>0</div>
            <div
              v-if="row.lastMonthSale && row.lastlastMonthSale && (row.lastlastMonthSale != row.lastMonthSale)"
              :class="dealSellNum(row.lastlastMonthSale,row.lastMonthSale).class"
            >{{ dealSellNum(row.lastlastMonthSale,row.lastMonthSale).str }}</div>
          </div>

        </template>
      </el-table-column>
      <el-table-column
        v-if="datas.tradeStatus == 1"
        type="tags"
        label="本月销量"
        align="center"
        prop="thisMonthSale"
        min-width="100px"
      >
        <template #default="{row}">
          <div class="tab-line">
            <div v-if="row.thisMonthSale">{{ row.thisMonthSale }}</div>
            <div v-else>0</div>
            <div
              v-if="row.lastMonthSale && row.thisMonthSale && (row.thisMonthSale != row.lastMonthSale)"
              :class="dealSellNum(row.lastMonthSale,row.thisMonthSale).class"
            >{{ dealSellNum(row.lastMonthSale,row.thisMonthSale).str }}</div>
          </div>

        </template>
      </el-table-column>
      <el-table-column
        type="tags"
        label="状态"
        fixed="right"
        align="center"
        min-width="150px"
      >
        <template #default="{row}">
          <div class="tab-line">
            <template v-if="(row.processDefinitionKey == 'agentProductCreate' || row.processDefinitionKey == 'agentPersonProductCreate')
                && (row.flowStatus=='DOING' || row.flowStatus=='REFUSE' || row.flowStatus=='REPEAL')">
              <span>{{ getLabel('approval_result',row.flowStatus) }}</span>
            </template>
            <template v-else>{{ getStatus(row) }}</template>
            <template v-if="row.flowStatus=='DOING'">
              <div
                v-if="row.processDefinitionKey == 'agentProductBan'"
                class="flow-status-color"
              >[作废审核中]</div>
              <div
                v-else-if="row.processDefinitionKey !== 'agentProductCreate' && row.processDefinitionKey !== 'agentPersonProductCreate'"
                class="flow-status-color"
              >[{{ getLabel('approval_result',row.flowStatus) }}]</div>
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        min-width="100px"
      >
        <template #default="{row}">
          <el-button
            v-if="row.agentProductStatus == 1"
            type="text"
            @click.stop="onRegister(row)"
          >注册终端</el-button>
          <template v-if="row.agentProductStatus == -1 && (row.flowStatus=='REFUSE' || row.flowStatus=='REPEAL' || row.flowStatus=='REJECT')">
            <el-button
              type="text"
              @click.stop="onEdit(row)"
            >编辑</el-button>
            <el-button
              type="text"
              class="delete-text-btn"
              @click.stop="onDelete(row)"
            >删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      :page="formData.page"
      :limit="formData.pageSize"
      style="display: flex; justify-content: flex-end"
      :total="total"
      @pagination="getListData"
    />

    <add-product-dialog
      ref="addProduct"
      :agent-id="datas.id"
      :type="type"
      :title="title"
      @success="onSuccess"
    />

    <change-product-dialog
      ref="changeProduct"
      :agent-id="datas.id"
      :agent-name="datas.agentName"
      :type="type"
      @success="onSuccess"
    />

    <invalid-product-dialog
      ref="invalidProduct"
      :agent-id="datas.id"
      :type="type"
      @success="onSuccess"
    />

    <change-price-dialog
      ref="changePrice"
      :type="type"
      :datas="datas"
      @success="onSuccess"
    />

    <register-terminal-dialog
      ref="registerTerminal"
      :agent="datas"
      :type="type"
      :agent-product="agentProduct"
    />

    <detail-drawer
      ref="detailDrawer"
      custom-title
      :size-width="1000"
    >
      <template #title>
        <div
          v-if="!isContract"
          style="display: flex;justify-content: space-between"
        >

          <div>
            <span>代理产品与价格-</span>
            <span class="drawerTitle">{{ agentProduct.agentProductNumber }}</span>
            <el-tag
              style="margin-left: 10px"
              type="warning"
              size="small"
            >
              <template v-if="(agentProduct.processDefinitionKey == 'agentProductCreate' || agentProduct.processDefinitionKey == 'agentPersonProductCreate')
                  && (agentProduct.flowStatus=='DOING' || agentProduct.flowStatus=='REFUSE' || agentProduct.flowStatus=='REPEAL')">
                <span>{{ getLabel('approval_result',agentProduct.flowStatus) }}</span>
              </template>
              <template v-else>{{ getStatus(agentProduct) }}</template>
              <template v-if="agentProduct.flowStatus=='DOING'">
                <span v-if="agentProduct.processDefinitionKey == 'agentProductBan'">[作废审核中]</span>
                <span v-else-if="agentProduct.processDefinitionKey !== 'agentProductCreate' && agentProduct.processDefinitionKey !== 'agentPersonProductCreate'">[{{ getLabel('approval_result',agentProduct.flowStatus) }}]</span>
              </template>
            </el-tag>

          </div>

          <div>
            <el-button
              v-if="agentProduct.agentProductStatus == 1"
              class="main-btn"
              size="small"
              type="primary"
              @click="changeClick"
            >变更信息</el-button>

            <el-button
              v-if="agentProduct.agentProductStatus == 1 && (agentProduct.processDefinitionKey !== 'agentProductBan' || (agentProduct.processDefinitionKey == 'agentProductBan' && agentProduct.flowStatus !=='DOING'))"
              class="main-btn"
              size="small"
              type="primary"
              @click="invalidClick"
            >作废</el-button>
          </div>

        </div>

        <div v-else>
          <span>合同 </span>

          <span class="drawerTitle">{{ agentProduct.contractName }}</span>
        </div>

      </template>
      <template #contents>
        <div v-if="!isContract">
          <item-title title="基本信息" />

          <product-and-price-detail-view
            :datas="datas"
            :agent-product="agentProduct"
            :type="type"
            @editPrice="editPrice"
            @contract="contractClick"
          />

          <item-title title="修改记录" />

          <operation-view
            :id="agentProduct.id"
            mode="agent_product"
          />
        </div>

        <div v-else>
          <contract-detail
            ref="salesDetailDrawer"
            :contract-id="agentProduct.contractId"
          />
        </div>

      </template>
    </detail-drawer>

  </div>
</template>

<script>
import {crmStore} from '../../../../../../store'
import contractDetail from '../../../../../commonView/contract/contractDetail.vue'
import registerTerminalDialog from './modules/registerTerminalDialog.vue'
import changePriceDialog from './modules/changePriceDialog.vue'
import invalidProductDialog from './modules/invalidProductDialog.vue'
import changeProductDialog from './modules/changeProductDialog.vue'
import productAndPriceDetailView from './modules/productAndPriceDetailView.vue'
import addProductDialog from './modules/addProductDialog.vue'
import {useRoute} from 'vue-router'
import {defineComponent, getCurrentInstance, inject, onBeforeMount, reactive, ref, toRefs,} from 'vue'

export default defineComponent({
  name: 'ProductAndPriceView',
  components: {
    addProductDialog,
    productAndPriceDetailView,
    changeProductDialog,
    invalidProductDialog,
    changePriceDialog,
    registerTerminalDialog,
    contractDetail,
  },
  props: {
    datas: {
      type: Object,
      default: {},
    },
    type: {
      type: String,
      default: 'agent',
    },
  },
  setup(props, context) {
    const route = useRoute()
    const api = inject('api')
    const currentInstance = getCurrentInstance()
    var detailDrawer = ref(null)
    var addProduct = ref(null)
    var changeProduct = ref(null)
    var invalidProduct = ref(null)
    var changePrice = ref(null)
    var registerTerminal = ref(null)
    var tableData = ref([])
    var total = ref(0)
    var agentProduct = ref({})
    var title = ref('新增代理产品与价格')
    var isContract = ref(false)
    var contractList = ref([])
    var headOptions = ref([])
    var data = reactive({
      formData: {
        page: 1,
        pageSize: 20,
        productId: '',
        agentProductStatus: '',
        agentAttribute: '',
        dateRange: [],
        headId: '',
        contractId: '',
      },
      loading: false,
      products: [],
      contractList: [],
      formList: [
        {
          key: 'agentProductStatus',
          label: '状态',
          form_type: 'select',
          value: '',
          is_search: false,
          options: [
            {
              value: '-2',
              label: '已作废',
            },
            {
              value: '-1',
              label: '无效',
            },
            {
              value: '1',
              label: '有效',
            },
          ],
        },
        {
          key: 'agentAttribute',
          label: '代理属性',
          form_type: 'select',
          value: '',
          is_search: false,
          options: crmStore.getters['dictionary/getDictionary'][props.type],
        },
        {
          key: 'dateRange',
          label: '代理期限至',
          form_type: 'daterange',
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: 'headId',
          label: '营销职员',
          form_type: 'select',
          value: '',
          is_search: false,
          options: headOptions,
        },
        {
          key: 'contractId',
          label: '关联代理合同',
          form_type: 'select',
          value: '',
          is_search: false,
          options: contractList,
        },
      ],
    })

    const dealSellNum = (last, now) => {
      if (last == now || !last || !now) {
        return {}
      }
      let classStr = ''
      let unit = ''
      const num = ((now - last) / last) * 100

      if (num < 0) {
        classStr = 'desc-num'
        unit = '↓'
      } else {
        classStr = 'asc-num'
        unit = '↑'
      }
      const str = num.toFixed(2) + '%' + unit
      return { class: classStr, str: str }
    }

    const remoteMethod = (query) => {
      data.products = []
      data.loading = true

      const a = {
        id: props.datas.id,
        productPopularName: '',
      }
      if (query) {
        a.productPopularName = query
      }

      api.signedAgent.AGENT_PRODUCT_PRODUCT_LIST(a).then((res) => {
        data.loading = false
        if (!res.code && res.data) {
          res.data.agentProduct.forEach((item) => {
            item.name =
              item.productPopularName + item.packSpecs + item.approvalNumber
          })
          data.products = res.data.agentProduct
        }
      })
    }

    const filterDataConfirm = (formdata) => {
      data.formData.page = 1
      data.formData.agentProductStatus = formdata.agentProductStatus
      data.formData.agentAttribute = formdata.agentAttribute
      data.formData.dateRange = formdata.dateRange
      data.formData.headId = formdata.headId
      data.formData.contractId = formdata.contractId
      getListData()
    }

    const listSearch = () => {
      data.formData.page = 1

      getListData()
    }

    const filterReset = () => {
      data.formData = {
        page: 1,
        pageSize: 20,
        productId: '',
        agentProductStatus: '',
        agentAttribute: '',
        dateRange: [],
        headId: '',
        contractId: '',
      }
      getListData()
    }

    const getListData = (id) => {
      const a = JSON.parse(JSON.stringify(data.formData))
      a.agentId = Number(route.query.id)
      a.productId = Number(a.productId)
      a.headId = Number(a.headId)
      a.contractId = Number(a.contractId)
      if (a.dateRange && a.dateRange.length > 1) {
        a.startTime = a.dateRange[0]
        a.endTime = a.dateRange[1]
      }
      api.signedAgent.AGENT_PRODUCT_LIST(a).then((res) => {
        if (!res.code && res.data) {
          tableData.value = res.data.list
          total.value = res.data.total
        }
      })
    }

    const getContract = () => {
      const a = {
        objectId: props.datas.id ? props.datas.id : Number(route.query.id),
        contractObjectType: props.type,
      }
      api.common.VALID_CONTRACT_LIST(a).then((res) => {
        if (!res.code && res.data) {
          res.data.list.forEach((item) => {
            item.value = item.id
            item.label = item.contractName
          })
          contractList.value = res.data.list
        }
      })
    }

    // 获取负责人
    const handlHead = () => {
      api.terminal.HEAD_PEOPLE(1).then((res) => {
        if (res.code === 0) {
          res.data.forEach((item) => {
            item.value = item.id
            item.label = item.realName
          })
          headOptions.value = res.data
        }
      })
    }

    onBeforeMount(() => {
      if (route.query.id) {
        getListData(route.query.id)
      }
      getContract()
      handlHead()
    })

    const addClick = () => {
      title.value = '新增代理产品与价格'
      addProduct.value.openDialog()
    }

    const onSuccess = () => {
      getListData(props.datas.id)

      if (agentProduct.value.id) {
        api.signedAgent
          .AGENT_PRODUCT_DETAIL(agentProduct.value.id)
          .then((res) => {
            if (!res.code && res.data) {
              agentProduct.value = res.data.agentProduct
            }
          })
      }
    }

    const getStatus = (row) => {
      switch (row.agentProductStatus) {
        case '-2':
          return '已作废'
        case '-1':
          return '无效'
        case '1':
          return '有效'
      }
    }

    const rowClick = (row) => {
      isContract.value = false
      api.signedAgent.AGENT_PRODUCT_DETAIL(row.id).then((res) => {
        if (!res.code && res.data) {
          agentProduct.value = res.data.agentProduct

          detailDrawer.value.open()
        }
      })
    }

    const contractClick = () => {
      isContract.value = true
    }

    const changeClick = () => {
      const a = JSON.parse(JSON.stringify(agentProduct.value))
      changeProduct.value.openDialog(a)
    }

    const invalidClick = () => {
      api.signedAgent
        .AGENT_PRODUCT_BANJUDGE(agentProduct.value.id)
        .then((res) => {
          if (!res.code && res.data) {
            if (res.data.inUse == 1) {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: '该代理与产品有关联的交易信息，暂时无法作废',
              })
            } else {
              const a = JSON.parse(JSON.stringify(agentProduct.value))
              invalidProduct.value.openDialog(a)
            }
          }
        })
    }

    const editPrice = () => {
      const a = JSON.parse(JSON.stringify(agentProduct.value))
      changePrice.value.openDialog(a)
    }

    const onRegister = (row) => {
      api.signedAgent.AGENT_PRODUCT_DETAIL(row.id).then((res) => {
        if (!res.code && res.data) {
          agentProduct.value = res.data.agentProduct

          registerTerminal.value.openDialog(agentProduct.value)
        }
      })
    }

    const onEdit = (row) => {
      title.value = '编辑代理产品与价格'
      addProduct.value.openDialog(row)
    }

    const onDelete = (row) => {
      currentInstance.proxy
        .alertBox({
          message: '是否确认删除该代理产品？',
          title: '删除',
        })
        .then(() => {
          api.signedAgent.AGENT_PRODUCT_DELETE(row.id).then((res) => {
            if (res.code) {
              // currentInstance.proxy.customMessage({type:'error',message:res.msg})
            } else {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: '删除成功',
              })
              getListData(route.query.id)
            }
          })
        })
        .catch((err) => {
          console.log(err)
        })
    }

    return {
      ...toRefs(data),
      addProduct,
      changeProduct,
      tableData,
      total,
      detailDrawer,
      agentProduct,
      invalidProduct,
      changePrice,
      registerTerminal,
      title,
      isContract,

      addClick,
      getListData,
      onSuccess,
      getStatus,
      rowClick,
      changeClick,
      invalidClick,
      editPrice,
      onRegister,
      onEdit,
      onDelete,
      contractClick,
      remoteMethod,
      filterDataConfirm,
      filterReset,
      listSearch,
      dealSellNum,
    }
  },
})
</script>

<style lang="scss" scoped>
@import "@/style/basics.scss";
.signed-agent-detail-product-view {
  .drawerTitle {
    font-size: 18px;
  }
  .desc-num {
    color: chartreuse;
  }
  .asc-num {
    color: $delete-color;
  }
}
</style>
